package org.fang.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.fang.common.PlatformResult;
import org.fang.pojo.CloudUser;
import org.fang.service.UserClientService;
import org.fang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author forsake
 * @Description
 * @Date 17:21 2022/3/9
 **/
@RestController
@RequestMapping("/hystrix")
public class UserController {
    @Qualifier("org.fang.service.UserClientService")
    @Autowired
    UserClientService service;

    @RequestMapping("/add")
    public PlatformResult add(@RequestBody CloudUser user) {
        PlatformResult add = service.add(user);
        return add;
    }

    /**
     * 没有查到则报异常
     * @param id
     * @return
     */
    @RequestMapping("/queryById/{id}")
    public PlatformResult queryById(@PathVariable("id") Integer id) {
        PlatformResult platformResult = service.queryById(id);
        if (Objects.isNull(platformResult.getData())) {
            // 直接报运行时异常到前端
            throw new RuntimeException();
        }
        return platformResult;
    }

    @RequestMapping("/queryById1/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet")
    public PlatformResult queryById1(@PathVariable("id") Integer id) {
        PlatformResult platformResult = service.queryById(id);
        if (Objects.isNull(platformResult.getData())) {
            // 抛出异常走到短路器方法
            throw new RuntimeException();
        }
        return platformResult;
    }

    /**
     * 断路器方法必须和原方法的参数列表相同，否则报错
     * @param id
     * @return
     */
    public PlatformResult hystrixGet(@PathVariable("id") Integer id) {
            return PlatformResult.success(new CloudUser().setUsername("，服务熔断，用户不存在"));
    }


}
